package app.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.PropertyResourceBundle;

public class BaseDao {
	private static String Driver;// 驱动
	private static String URL;// 地址ַ
	private static String USERNAME;// 数据库用户名
	private static String PASSWORD;// 数据库密码
	private static PropertyResourceBundle  resourceBundle;

	public static void init() {
		try {
			resourceBundle = new PropertyResourceBundle(
					BaseDao.class.getResourceAsStream("db.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// properties.list(System.out);
		BaseDao.Driver = resourceBundle.getString("Driver");
		BaseDao.URL = resourceBundle.getString("URL");
		BaseDao.USERNAME = resourceBundle.getString("USERNAME");
		BaseDao.PASSWORD = resourceBundle.getString("PASSWORD");
	}

	// 打开链接
	public static Connection getcon() {
		BaseDao.init();
		Connection con = null;
		try {
			Class.forName(Driver);// 加载驱动
			con = DriverManager.getConnection(URL, USERNAME, PASSWORD);// 打开链接
			System.out.println("数据库连接中。。。");
			if (con != null) {
				System.out.println("连接成功！\n");
			} else {
				System.out.println("连接失败！");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

	// 执行增加删除修改
	public static int excute(String sql, Object... obj) {
		// TODO Auto-generated method stub
		int num = -1;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet r = null;
		try {
			con = getcon();
			ps = con.prepareStatement(sql);
			if (obj != null) {
				for (int i = 0; i < obj.length; i++) {
					ps.setObject(i + 1, obj[i]);
				}
			}
			num = ps.executeUpdate();
			System.out.println(sql);
			System.out.println("(" + num + "(rows) affected" + ")");
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(con, ps, r);
		}
		return num;
	}

	// 释放资源
	public static void closeAll(Connection con, PreparedStatement ps,
			ResultSet r) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (r != null) {
			try {
				r.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
